import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/paging/model/paging_datas.dart';
import 'package:yt_devops/components/paging/model/paging_params.dart';
import 'package:yt_devops/components/paging/page_controller.dart';
import 'package:yt_devops/components/yt_bottom_picker.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_product_type_model.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_status_tags.dart';
import 'package:yt_devops/resources/str_res_keys.dart';

import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/alarm_util.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

import 'package:yt_devops/utils/navigate_utils.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';

import 'components/filter_product_tags.dart';
import 'device_list_model.dart';

class DeviceListController
    extends PagingController<DeviceListModel, DeviceListState> {
  DeviceServices services = Get.put(DeviceServices());
  List<DeviceProductTypeModel> typeList = [];
  bool isLoad = false;
  int fromType = 0;
  int? selectedIndex = 0;

  ///
  bool lock = false;

  TextEditingController searchTextEditingController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    getDeviceType();
    if (Get.arguments is int) {
      fromType = Get.arguments;
    }
  }

  @override
  void onReady() {
    Log.d('DeviceListController==');
  }

  @override
  void onClose() {}

  @override
  getState() {
    return DeviceListState();
  }

  @override
  Future<PagingDatas<DeviceListModel>?> loadData(
      PagingParams pagingParams) async {
    lock = true;
    // if (!isLoad) showLoading(toast: ResKey.loading.tr);

    var json = await services.getDevicelist(
      {
        'current': pagingParams.pageNum,
        'pageSize': pagingParams.pageSize,
        'siteId': pagingState.siteId,
        'productTypeId': pagingState.productTypeEnity?.id,
        'productId': pagingState.productTypeEnity?.subProduct?.id,
        'connectStatus': pagingState.connectStatus?.value ?? '',
        'name': pagingState.name ?? '',
        'sn': pagingState.sn ?? '',
        'alarmStatus': pagingState.alarmStatus?.value ?? '',
        'snOrName': pagingState.snOrName,
        'rootFilter': 1,
        'isFindParentByChild': 1
      },
      onError: (p0) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        refreshController.loadComplete();
        refreshController.refreshCompleted();
        // dismissLoading();
        handleException(p0);
        lock = false;
        return false;
      },
    );
    if (!isLoad) {
      isLoad = true;
      // dismissLoading();
    }

    lock = false;

    return PagingDatas<DeviceListModel>.fromJson(json);
  }

  // 获取设备类型
  Future getDeviceType() async =>
      await Configs.httpClient.requestWithLoading(() async {
        var data = await services.getProductTypelist();
        typeList = List.of(data)
            .map((e) => DeviceProductTypeModel.fromJson(e))
            .toList();
      }, showLoading: false);

  tapDeviceHandler(DeviceListModel device) {
    Log.d("设备列表的设备单元点击事件111 ==== ${device.productId}");
    if (Get.arguments == 1) {
      // 从添加维修任务来
      Get.back(result: device);
    } else {
      AlarmUtil.fromModule = AlarmFromWhereType.device.value;
      Log.d("设备列表的设备单元点击事件 ==== ${device.productId}");

      NavigateUtils.toDeviceDetail(
        device.deviceId!,
        device.productType!,
        device.name ?? '',
        device.connectStatus!,
        productId: device.productId,
        deviceTree: device,
      );
    }
  }

  resetFilter(void Function(void Function()) setState) {
    setState(() {
      pagingState.alarmStatus = null;
      pagingState.connectStatus = null;
      pagingState.productTypeEnity = null;
      pagingState.selectedSites.clear();
    });
  }

  // 去添加设备
  void toAddDevice() {
    Get.toNamed(RouterPath.siteDeviceAccess);
  }

  T? onStatusChange<T>(List<T> list, T? curState, int? index) {
    switch (index) {
      case null:
        return curState;
      case 0:
        return null;
      default:
        return list[index - 1];
    }
  }

  ///过滤弹窗
  toFilter(BuildContext context) async {
    int? connectIndex;
    int? alarmIndex;
    ProductTypeEnity? productTypes;
    List<SiteTagModel>? sites;

    await getDeviceType();

    ytBottomPicker(
      context,
      minHeight: 462.h,
      mainButtonOnTap: () {
        isLoad = false;
        pagingState.connectStatus = onStatusChange(
            ConnectStatusType.values, pagingState.connectStatus, connectIndex);
        pagingState.alarmStatus = onStatusChange(
            DeviceAlarmStatus.values, pagingState.alarmStatus, alarmIndex);
        pagingState.productTypeEnity =
            productTypes ?? pagingState.productTypeEnity;
        pagingState.selectedSites = sites ?? pagingState.selectedSites;

        Get.back();
        refreshData(isSearch: true);
      },
      resetTap: (setstate) {
        sites = [];
        connectIndex = null;
        alarmIndex = null;
        productTypes = null;

        resetFilter(setstate);
      },
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 站点
              FilterSiteTags(
                selectedSites: pagingState.selectedSites,
                onChange: (siteList) {
                  sites = siteList;
                },
              ),
              FilterStatusTags<ConnectStatusType>(
                ConnectStatusType.values,
                labelName: (status) => status.label,
                tagWidth: 75.w,
                title: ResKey.deviceCommunicationStatus.tr,
                selectTags: pagingState.connectStatus == null
                    ? []
                    : [pagingState.connectStatus!],
                onSingleSelect: (index, status) {
                  connectIndex = index;
                },
              ),

              FilterStatusTags<DeviceAlarmStatus>(
                DeviceAlarmStatus.values,
                labelName: (status) => status.label,
                title: ResKey.alarmStatus.tr,
                selectTags: pagingState.alarmStatus == null
                    ? []
                    : [pagingState.alarmStatus!],
                onSingleSelect: (int index, stuatus) {
                  alarmIndex = index;
                },
              ),

              FilterProductTags(
                pagingState.productTypeEnity,
                onSelect: (p) => productTypes = p,
              ),
            ],
          ),
        );
      },
    );
  }
}
